package com.example.logisticsingle.filter;


import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.entity.SSOUser;

import com.example.logisticsingle.login.SSOTokenLoginHelper;
import com.example.logisticsingle.path.AntPathMatcher;
import com.example.logisticsingle.utils.CookieUtil;


import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  web sso filter
 *
 */
@Slf4j
public class SSOWebTokenFilter extends HttpServlet implements Filter {
    /**
     *
     */
    private static final long serialVersionUID = -7226643459445328536L;
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private String ssoServer;
    private String logoutPath;
    private String excludedPaths;

    public void init(FilterConfig filterConfig) throws ServletException {
        ssoServer = filterConfig.getInitParameter(Config.SSO_SERVER);
        logoutPath = filterConfig.getInitParameter(Config.SSO_LOGOUT_PATH);
        excludedPaths = filterConfig.getInitParameter(Config.SSO_EXCLUDED_PATHS);
        log.info("SsoWebTokenFilter init.");
    }



    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String servletPath = req.getServletPath();
        /**
         * 	 无须要授权操作URL
         */
        if( (excludedPaths!=null && excludedPaths.trim().length()>0) ){
            for (String excludedPath:excludedPaths.split(",")) {
                String uriPattern = excludedPath.trim();

                // 支持ANT表达式
                if (antPathMatcher.match(uriPattern, servletPath)) {
                    // excluded path, allow
                    chain.doFilter(request, response);
                    return;
                }

            }
        }
        // logout path check
        if (logoutPath!=null
                && logoutPath.trim().length()>0
                && logoutPath.equals(servletPath)) {

            // remove cookie
            CookieUtil.remove(req, res, Config.SSO_SESSIONID);

            // redirect logout
            String logoutPageUrl = ssoServer.concat(Config.SSO_LOGOUT);
            res.sendRedirect(logoutPageUrl);
            return;
        }
        // valid login user, cookie + redirect
        SSOUser ssoUser = SSOTokenLoginHelper.loginCheck(req);
        // valid login fail
        if (ssoUser == null) {

            String header = req.getHeader("content-type");
            boolean isJson=  header!=null && header.contains("json");
            if (isJson) {

                // json msg
                res.setContentType("application/json;charset=utf-8");
                res.getWriter().println("{\"code\":"+501+", \"msg\":\""+ "sso not login." +"\"}");
                return;
            } else {

                // total link
                String link = req.getRequestURL().toString();

                // redirect logout
                String loginPageUrl = ssoServer.concat(Config.SSO_LOGIN)
                        + "?" + Config.REDIRECT_URL + "=" + link;

                res.sendRedirect(loginPageUrl);
                return;
            }

        }
        // ser sso user
        request.setAttribute(Config.SSO_USER, ssoUser);

        // already login, allow
        chain.doFilter(request, response);
        return;
    }
}
